home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.004 / xemacs-1 / xemacs-19.13 / src / regex.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-08-15  |  46.9 KB  |  1,827 lines

  1. /* Extended regular expression matching and search.
  2.    Copyright (C) 1985, 1992, 1993, 1994 Free Software Foundation, Inc.
  3.  
  4. This file is part of XEmacs.
  5.  
  6. XEmacs is free software; you can redistribute it and/or modify it
  7. under the terms of the GNU General Public License as published by the
  8. Free Software Foundation; either version 2, or (at your option) any
  9. later version.
  10.  
  11. XEmacs is distributed in the hope that it will be useful, but WITHOUT
  12. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14. for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with XEmacs; see the file COPYING.  If not, write to the Free
  18. Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /* Synched up with: Not synched with FSF.  FSF 19 has a rewritten regex.c
  21.    that is not used by XEmacs (this version comes from Emacs 18). */
  22.  
  23.  
  24. /* To test, compile with -Dtest.
  25.  This Dtestable feature turns this into a self-contained program
  26.  which reads a pattern, describes how it compiles,
  27.  then reads a string and searches for it.  */
  28.  
  29. /* define this to add in a speedup for patterns anchored at the beginning
  30.    of a line.  (Even when we're sure this works, keep the ifdefs so that
  31.    it's easier to tell where/why this code has diverged from v18.)
  32.  */
  33. #define REGEX_BEGLINE_CHECK
  34.  
  35. #ifdef emacs
  36.  
  37. /* The `emacs' switch turns on certain special matching commands
  38.  that make sense only in emacs. */
  39.  
  40. #include <config.h>
  41. #include "lisp.h"
  42. #include "buffer.h"
  43. #include "syntax.h"
  44.  
  45. #else  /* not emacs */
  46.  
  47. /*
  48.  * Define the syntax stuff, so we can do the \<...\> things.
  49.  */
  50.  
  51. #ifndef Sword /* must be non-zero in some of the tests below... */
  52. #define Sword 1
  53. #endif
  54.  
  55. #define SYNTAX(ignored,c) re_syntax_table[c]
  56.  
  57. #ifdef SYNTAX_TABLE
  58.  
  59. char *re_syntax_table;
  60.  
  61. #else
  62.  
  63. static char re_syntax_table[256];
  64.  
  65. static void
  66. init_syntax_once ()
  67. {
  68.    int c;
  69.    static int done = 0;
  70.  
  71.    if (done)
  72.      return;
  73.  
  74.    memset (re_syntax_table, 0, sizeof re_syntax_table);
  75.  
  76.    for (c = 'a'; c <= 'z'; c++)
  77.      re_syntax_table[c] = Sword;
  78.  
  79.    for (c = 'A'; c <= 'Z'; c++)
  80.      re_syntax_table[c] = Sword;
  81.  
  82.    for (c = '0'; c <= '9'; c++)
  83.      re_syntax_table[c] = Sword;
  84.  
  85.    done = 1;
  86. }
  87.  
  88. #endif /* SYNTAX_TABLE */
  89. #endif /* not emacs */
  90.  
  91. #include "regex.h"
  92.  
  93. /* Number of failure points to allocate space for initially,
  94.  when matching.  If this number is exceeded, more space is allocated,
  95.  so it is not a hard limit.  */
  96.  
  97. #ifndef NFAILURES
  98. #define NFAILURES 80
  99. #endif /* NFAILURES */
  100.  
  101. /* width of a byte in bits */
  102.  
  103. #define BYTEWIDTH 8
  104.  
  105. /* We remove any previous definition of `SIGN_EXTEND_CHAR',
  106.    since ours (we hope) works properly with all combinations of
  107.    machines, compilers, `char' and `unsigned char' argument types.
  108.    (Per Bothner suggested the basic approach.)  */
  109. #undef SIGN_EXTEND_CHAR
  110. #if __STDC__ || defined(STDC_HEADERS)
  111. #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
  112. #else  /* not __STDC__ */
  113. /* As in Harbison and Steele.  */
  114. #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
  115. #endif
  116.  
  117. static int obscure_syntax = 0;
  118.  
  119. /* Specify the precise syntax of regexp for compilation.
  120.    This provides for compatibility for various utilities
  121.    which historically have different, incompatible syntaxes.
  122.  
  123.    The argument SYNTAX is a bit-mask containing the two bits
  124.    RE_NO_BK_PARENS and RE_NO_BK_VBAR.  */
  125.  
  126. #if 0
  127. int
  128. re_set_syntax (syntax)
  129.      int syntax;
  130. {
  131.   int ret;
  132.  
  133.   ret = obscure_syntax;
  134.   obscure_syntax = syntax;
  135.   return ret;
  136. }
  137. #endif /* unused */
  138.  
  139. /* re_compile_pattern takes a regular-expression string
  140.    and converts it into a buffer full of byte commands for matching.
  141.  
  142.   PATTERN   is the address of the pattern string
  143.   SIZE      is the length of it.
  144.   BUFP        is a  struct re_pattern_buffer *  which points to the info
  145.         on where to store the byte commands.
  146.         This structure contains a  char *  which points to the
  147.         actual space, which should have been obtained with malloc.
  148.         re_compile_pattern may use  realloc  to grow the buffer space.
  149.  
  150.   The number of bytes of commands can be found out by looking in
  151.   the  struct re_pattern_buffer  that bufp pointed to,
  152.   after re_compile_pattern returns.
  153. */
  154.  
  155. #define PATPUSH(ch) (*b++ = (char) (ch))
  156.  
  157. #define PATFETCH(c) \
  158.  {if (p == pend) goto end_of_pattern; \
  159.   c = * (unsigned char *) p++; \
  160.   if (translate) c = translate[c]; }
  161.  
  162. #define PATFETCH_RAW(c) \
  163.  {if (p == pend) goto end_of_pattern; \
  164.   c = * (unsigned char *) p++; }
  165.  
  166. #define PATUNFETCH p--
  167.  
  168. #define EXTEND_BUFFER \
  169.   { char *old_buffer = bufp->buffer; \
  170.     if (bufp->allocated == (1<<16)) goto too_big; \
  171.     bufp->allocated *= 2; \
  172.     if (bufp->allocated > (1<<16)) bufp->allocated = (1<<16); \
  173.     if (!(bufp->buffer = (char *) xrealloc (bufp->buffer, bufp->allocated))) \
  174.       goto memory_exhausted; \
  175.     c = bufp->buffer - old_buffer; \
  176.     b += c; \
  177.     if (fixup_jump) \
  178.       fixup_jump += c; \
  179.     if (laststart) \
  180.       laststart += c; \
  181.     begalt += c; \
  182.     if (pending_exact) \
  183.       pending_exact += c; \
  184.   }
  185.  
  186. static void store_jump (char *from, char opcode, char *to);
  187. static void insert_jump (char op, char *from, char *to, char *current_end);
  188.  
  189. char *
  190. re_compile_pattern (char *pattern, int size, struct re_pattern_buffer *bufp)
  191. {
  192.   char *b = bufp->buffer;
  193.   char *p = pattern;
  194.   char *pend = pattern + size;
  195.   char *p1;
  196.   unsigned long c, c1;
  197.   unsigned char *translate = (unsigned char *) bufp->translate;
  198.  
  199.   /* address of the count-byte of the most recently inserted "exactn" command.
  200.     This makes it possible to tell whether a new exact-match character
  201.     can be added to that command or requires a new "exactn" command. */
  202.      
  203.   char *pending_exact = 0;
  204.  
  205.   /* address of the place where a forward-jump should go
  206.     to the end of the containing expression.
  207.     Each alternative of an "or", except the last, ends with a forward-jump
  208.     of this sort. */
  209.  
  210.   char *fixup_jump = 0;
  211.  
  212.   /* address of start of the most recently finished expression.
  213.     This tells postfix * where to find the start of its operand. */
  214.  
  215.   char *laststart = 0;
  216.  
  217.   /* In processing a repeat, 1 means zero matches is allowed */
  218.  
  219.   char zero_times_ok;
  220.  
  221.   /* In processing a repeat, 1 means many matches is allowed */
  222.  
  223.   char many_times_ok;
  224.  
  225.   /* address of beginning of regexp, or inside of last \( */
  226.  
  227.   char *begalt = b;
  228.  
  229.   /* Stack of information saved by \( and restored by \).
  230.      Four stack elements are pushed by each \(:
  231.        First, the value of b.
  232.        Second, the value of fixup_jump.
  233.        Third, the value of regnum.
  234.        Fourth, the value of begalt.  */
  235.  
  236.   int stackb[40];
  237.   int *stackp = stackb;
  238.   int *stacke = stackb + 40;
  239.   int *stackt;
  240.  
  241.   /* Counts \('s as they are encountered.  Remembered for the matching \),
  242.      where it becomes the "register number" to put in the stop_memory command */
  243.  
  244.   int regnum = 1;
  245.  
  246.   bufp->fastmap_accurate = 0;
  247.  
  248. #ifndef emacs
  249. #ifndef SYNTAX_TABLE
  250.   /*
  251.    * Initialize the syntax table.
  252.    */
  253.    init_syntax_once();
  254. #endif
  255. #endif
  256.  
  257.   if (bufp->allocated == 0)
  258.     {
  259.       bufp->allocated = 28;
  260.       if (bufp->buffer)
  261.     /* EXTEND_BUFFER loses when bufp->allocated is 0 */
  262.     bufp->buffer = (char *) xrealloc (bufp->buffer, 28);
  263.       else
  264.     /* Caller did not allocate a buffer.  Do it for him */
  265.     bufp->buffer = (char *) xmalloc (28);
  266.       if (!bufp->buffer) goto memory_exhausted;
  267.       begalt = b = bufp->buffer;
  268.     }
  269.  
  270.   while (p != pend)
  271.     {
  272.       if (b - bufp->buffer > bufp->allocated - 10)
  273.     /* Note that EXTEND_BUFFER clobbers c */
  274.     EXTEND_BUFFER;
  275.  
  276.       PATFETCH (c);
  277.  
  278.       switch (c)
  279.     {
  280.     case '$':
  281.       if (obscure_syntax & RE_TIGHT_VBAR)
  282.         {
  283.           if (! (obscure_syntax & RE_CONTEXT_INDEP_OPS) && p != pend)
  284.         goto normal_char;
  285.           /* Make operand of last vbar end before this `$'.  */
  286.           if (fixup_jump)
  287.         store_jump (fixup_jump, jump, b);
  288.           fixup_jump = 0;
  289.           PATPUSH (endline);
  290.           break;
  291.         }
  292.  
  293.       /* $ means succeed if at end of line, but only in special contexts.
  294.         If randomly in the middle of a pattern, it is a normal character. */
  295.       if (p == pend || *p == '\n'
  296.           || (obscure_syntax & RE_CONTEXT_INDEP_OPS)
  297.           || (obscure_syntax & RE_NO_BK_PARENS
  298.           ? *p == ')'
  299.           : *p == '\\' && p[1] == ')')
  300.           || (obscure_syntax & RE_NO_BK_VBAR
  301.           ? *p == '|'
  302.           : *p == '\\' && p[1] == '|'))
  303.         {
  304.           PATPUSH (endline);
  305.           break;
  306.         }
  307.       goto normal_char;
  308.  
  309.     case '^':
  310.       /* ^ means succeed if at beg of line, but only if no preceding pattern. */
  311.  
  312.       if (laststart && p[-2] != '\n'
  313.           && ! (obscure_syntax & RE_CONTEXT_INDEP_OPS))
  314.         goto normal_char;
  315.       if (obscure_syntax & RE_TIGHT_VBAR)
  316.         {
  317.           if (p != pattern + 1
  318.           && ! (obscure_syntax & RE_CONTEXT_INDEP_OPS))
  319.         goto normal_char;
  320.           PATPUSH (begline);
  321.           begalt = b;
  322.         }
  323.       else
  324.         PATPUSH (begline);
  325.       break;
  326.  
  327.     case '+':
  328.     case '?':
  329.       if (obscure_syntax & RE_BK_PLUS_QM)
  330.         goto normal_char;
  331.     handle_plus:
  332.     case '*':
  333.       /* If there is no previous pattern, char not special. */
  334.       if (!laststart && ! (obscure_syntax & RE_CONTEXT_INDEP_OPS))
  335.         goto normal_char;
  336.       /* If there is a sequence of repetition chars,
  337.          collapse it down to equivalent to just one.  */
  338.       zero_times_ok = 0;
  339.       many_times_ok = 0;
  340.       while (1)
  341.         {
  342.           zero_times_ok |= c != '+';
  343.           many_times_ok |= c != '?';
  344.           if (p == pend)
  345.         break;
  346.           PATFETCH (c);
  347.           if (c == '*')
  348.         ;
  349.           else if (!(obscure_syntax & RE_BK_PLUS_QM)
  350.                && (c == '+' || c == '?'))
  351.         ;
  352.           else if ((obscure_syntax & RE_BK_PLUS_QM)
  353.                && c == '\\')
  354.         {
  355.           PATFETCH (c1);
  356.           if (!(c1 == '+' || c1 == '?'))
  357.             {
  358.               PATUNFETCH;
  359.               PATUNFETCH;
  360.               break;
  361.             }
  362.           c = c1;
  363.         }
  364.           else
  365.         {
  366.           PATUNFETCH;
  367.           break;
  368.         }
  369.         }
  370.  
  371.       /* Star, etc. applied to an empty pattern is equivalent
  372.          to an empty pattern.  */
  373.       if (!laststart)
  374.         break;
  375.  
  376.       /* Now we know whether 0 matches is allowed,
  377.          and whether 2 or more matches is allowed.  */
  378.       if (many_times_ok)
  379.         {
  380.           /* If more than one repetition is allowed,
  381.          put in a backward jump at the end.  */
  382.           store_jump (b, maybe_finalize_jump, laststart - 3);
  383.           b += 3;
  384.         }
  385.       insert_jump (on_failure_jump, laststart, b + 3, b);
  386.       pending_exact = 0;
  387.       b += 3;
  388.       if (!zero_times_ok)
  389.         {
  390.           /* At least one repetition required: insert before the loop
  391.          a skip over the initial on-failure-jump instruction */
  392.           insert_jump (dummy_failure_jump, laststart, laststart + 6, b);
  393.           b += 3;
  394.         }
  395.       break;
  396.  
  397.     case '.':
  398.       laststart = b;
  399.       PATPUSH (anychar);
  400.       break;
  401.  
  402.     case '[':
  403.       while (b - bufp->buffer
  404.          > bufp->allocated - 3 - (1 << BYTEWIDTH) / BYTEWIDTH)
  405.         /* Note that EXTEND_BUFFER clobbers c */
  406.         EXTEND_BUFFER;
  407.  
  408.       laststart = b;
  409.       if (*p == '^')
  410.         PATPUSH (charset_not), p++;
  411.       else
  412.         PATPUSH (charset);
  413.       p1 = p;
  414.  
  415.       PATPUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
  416.       /* Clear the whole map */
  417.       memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
  418.       /* Read in characters and ranges, setting map bits */
  419.       while (1)
  420.         {
  421.           PATFETCH (c);
  422.           if (c == ']' && p != p1 + 1) break;
  423.           if (*p == '-' && p[1] != ']')
  424.         {
  425.           PATFETCH (c1);
  426.           PATFETCH (c1);
  427.           while (c <= c1)
  428.             b[c / BYTEWIDTH] |= 1 << (c % BYTEWIDTH), c++;
  429.         }
  430.           else
  431.         {
  432.           b[c / BYTEWIDTH] |= 1 << (c % BYTEWIDTH);
  433.         }
  434.         }
  435.       /* Discard any bitmap bytes that are all 0 at the end of the map.
  436.          Decrement the map-length byte too. */
  437.       while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
  438.         b[-1]--;
  439.       b += b[-1];
  440.       break;
  441.  
  442.     case '(':
  443.       if (! (obscure_syntax & RE_NO_BK_PARENS))
  444.         goto normal_char;
  445.       else
  446.         goto handle_open;
  447.  
  448.     case ')':
  449.       if (! (obscure_syntax & RE_NO_BK_PARENS))
  450.         goto normal_char;
  451.       else
  452.         goto handle_close;
  453.  
  454.     case '\n':
  455.       if (! (obscure_syntax & RE_NEWLINE_OR))
  456.         goto normal_char;
  457.       else
  458.         goto handle_bar;
  459.  
  460.     case '|':
  461.       if (! (obscure_syntax & RE_NO_BK_VBAR))
  462.         goto normal_char;
  463.       else
  464.         goto handle_bar;
  465.  
  466.         case '\\':
  467.       if (p == pend) goto invalid_pattern;
  468.       PATFETCH_RAW (c);
  469.       switch (c)
  470.         {
  471.         case '(':
  472.           if (obscure_syntax & RE_NO_BK_PARENS)
  473.         goto normal_backsl;
  474.         handle_open:
  475.           if (stackp == stacke) goto nesting_too_deep;
  476.           if (regnum < RE_NREGS)
  477.             {
  478.           PATPUSH (start_memory);
  479.           PATPUSH (regnum);
  480.             }
  481.           *stackp++ = b - bufp->buffer;
  482.           *stackp++ = fixup_jump ? fixup_jump - bufp->buffer + 1 : 0;
  483.           *stackp++ = regnum++;
  484.           *stackp++ = begalt - bufp->buffer;
  485.           fixup_jump = 0;
  486.           laststart = 0;
  487.           begalt = b;
  488.           break;
  489.  
  490.         case ')':
  491.           if (obscure_syntax & RE_NO_BK_PARENS)
  492.         goto normal_backsl;
  493.         handle_close:
  494.           if (stackp == stackb) goto unmatched_close;
  495.           begalt = *--stackp + bufp->buffer;
  496.           if (fixup_jump)
  497.         store_jump (fixup_jump, jump, b);
  498.           if (stackp[-1] < RE_NREGS)
  499.         {
  500.           PATPUSH (stop_memory);
  501.           PATPUSH (stackp[-1]);
  502.         }
  503.           stackp -= 2;
  504.           fixup_jump = 0;
  505.           if (*stackp)
  506.         fixup_jump = *stackp + bufp->buffer - 1;
  507.           laststart = *--stackp + bufp->buffer;
  508.           break;
  509.  
  510.         case '|':
  511.           if (obscure_syntax & RE_NO_BK_VBAR)
  512.         goto normal_backsl;
  513.         handle_bar:
  514.           insert_jump (on_failure_jump, begalt, b + 6, b);
  515.           pending_exact = 0;
  516.           b += 3;
  517.           if (fixup_jump)
  518.         store_jump (fixup_jump, jump, b);
  519.           fixup_jump = b;
  520.           b += 3;
  521.           laststart = 0;
  522.           begalt = b;
  523.           break;
  524.  
  525. #ifdef emacs
  526.         case '=':
  527.           PATPUSH (at_dot);
  528.           break;
  529.  
  530.         case 's':    
  531.           laststart = b;
  532.           PATPUSH (syntaxspec);
  533.           PATFETCH (c);
  534.           PATPUSH (syntax_spec_code[c]);
  535.           break;
  536.  
  537.         case 'S':
  538.           laststart = b;
  539.           PATPUSH (notsyntaxspec);
  540.           PATFETCH (c);
  541.           PATPUSH (syntax_spec_code[c]);
  542.           break;
  543. #endif /* emacs */
  544.  
  545.         case 'w':
  546.           laststart = b;
  547.           PATPUSH (wordchar);
  548.           break;
  549.  
  550.         case 'W':
  551.           laststart = b;
  552.           PATPUSH (notwordchar);
  553.           break;
  554.  
  555.         case '<':
  556.           PATPUSH (wordbeg);
  557.           break;
  558.  
  559.         case '>':
  560.           PATPUSH (wordend);
  561.           break;
  562.  
  563.         case 'b':
  564.           PATPUSH (wordbound);
  565.           break;
  566.  
  567.         case 'B':
  568.           PATPUSH (notwordbound);
  569.           break;
  570.  
  571.         case '`':
  572.           PATPUSH (begbuf);
  573.           break;
  574.  
  575.         case '\'':
  576.           PATPUSH (endbuf);
  577.           break;
  578.  
  579.         case '1':
  580.         case '2':
  581.         case '3':
  582.         case '4':
  583.         case '5':
  584.         case '6':
  585.         case '7':
  586.         case '8':
  587.         case '9':
  588.           c1 = c - '0';
  589.           if (c1 >= regnum)
  590.         goto normal_char;
  591.           for (stackt = stackp - 2;  stackt > stackb;  stackt -= 4)
  592.          if (*stackt == c1)
  593.           goto normal_char;
  594.           laststart = b;
  595.           PATPUSH (duplicate);
  596.           PATPUSH (c1);
  597.           break;
  598.  
  599.         case '+':
  600.         case '?':
  601.           if (obscure_syntax & RE_BK_PLUS_QM)
  602.         goto handle_plus;
  603.  
  604.         default:
  605.         normal_backsl:
  606.           /* You might think it would be useful for \ to mean
  607.          not to translate; but if we don't translate it
  608.          it will never match anything.  */
  609.           if (translate) c = translate[c];
  610.           goto normal_char;
  611.         }
  612.       break;
  613.  
  614.     default:
  615.     normal_char:
  616.       if (!pending_exact || pending_exact + *pending_exact + 1 != b
  617.           || *pending_exact == 0177 || *p == '*' || *p == '^'
  618.           || ((obscure_syntax & RE_BK_PLUS_QM)
  619.           ? *p == '\\' && (p[1] == '+' || p[1] == '?')
  620.           : (*p == '+' || *p == '?')))
  621.         {
  622.           laststart = b;
  623.           PATPUSH (exactn);
  624.           pending_exact = b;
  625.           PATPUSH (0);
  626.         }
  627.       PATPUSH (c);
  628.       (*pending_exact)++;
  629.     }
  630.     }
  631.  
  632.   if (fixup_jump)
  633.     store_jump (fixup_jump, jump, b);
  634.  
  635.   if (stackp != stackb) goto unmatched_open;
  636.  
  637.   bufp->used = b - bufp->buffer;
  638.   return 0;
  639.  
  640.  invalid_pattern:
  641.   return GETTEXT ("Invalid regular expression");
  642.  
  643.  unmatched_open:
  644.   return GETTEXT ("Unmatched \\(");
  645.  
  646.  unmatched_close:
  647.   return GETTEXT ("Unmatched \\)");
  648.  
  649.  end_of_pattern:
  650.   return GETTEXT ("Premature end of regular expression");
  651.  
  652.  nesting_too_deep:
  653.   return GETTEXT ("Nesting too deep");
  654.  
  655.  too_big:
  656.   return GETTEXT ("Regular expression too big");
  657.  
  658.  memory_exhausted:
  659.   return GETTEXT ("Memory exhausted");
  660. }
  661.  
  662. /* Store where `from' points a jump operation to jump to where `to' points.
  663.   `opcode' is the opcode to store. */
  664.  
  665. static void
  666. store_jump (char *from, char opcode, char *to)
  667. {
  668.   from[0] = opcode;
  669.   from[1] = (to - (from + 3)) & 0377;
  670.   from[2] = (to - (from + 3)) >> 8;
  671. }
  672.  
  673. /* Open up space at char FROM, and insert there a jump to TO.
  674.    CURRENT_END gives te end of the storage no in use,
  675.    so we know how much data to copy up.
  676.    OP is the opcode of the jump to insert.
  677.  
  678.    If you call this function, you must zero out pending_exact.  */
  679.  
  680. static void
  681. insert_jump (char op, char *from, char *to, char *current_end)
  682. {
  683.   char *pto = current_end + 3;
  684.   char *pfrom = current_end;
  685.   while (pfrom != from)
  686.     *--pto = *--pfrom;
  687.   store_jump (from, op, to);
  688. }
  689.  
  690. /* Given a pattern, compute a fastmap from it.
  691.  The fastmap records which of the (1 << BYTEWIDTH) possible characters
  692.  can start a string that matches the pattern.
  693.  This fastmap is used by re_search to skip quickly over totally implausible text.
  694.  
  695.  The caller must supply the address of a (1 << BYTEWIDTH)-byte data area
  696.  as bufp->fastmap.
  697.  The other components of bufp describe the pattern to be used.  */
  698.  
  699. static void
  700. re_compile_fastmap (struct re_pattern_buffer *bufp)
  701. {
  702.   unsigned char *pattern = (unsigned char *) bufp->buffer;
  703.   int size = bufp->used;
  704.   char *fastmap = bufp->fastmap;
  705.   unsigned char *p = pattern;
  706.   unsigned char *pend = pattern + size;
  707.   int j, k;
  708.   unsigned char *translate = (unsigned char *) bufp->translate;
  709.  
  710.   unsigned char *stackb[NFAILURES];
  711.   unsigned char **stackp = stackb;
  712.  
  713. #ifdef emacs
  714.   Lisp_Object syntax_table = current_buffer->syntax_table;
  715. #endif
  716.  
  717.   memset (fastmap, 0, (1 << BYTEWIDTH));
  718.   bufp->fastmap_accurate = 1;
  719.   bufp->can_be_null = 0;
  720.       
  721.   while (p)
  722.     {
  723.       if (p == pend)
  724.     {
  725.       bufp->can_be_null = 1;
  726.       break;
  727.     }
  728. #ifdef SWITCH_ENUM_BUG
  729.       switch ((int) ((enum regexpcode) *p++))
  730. #else
  731.       switch ((enum regexpcode) *p++)
  732. #endif
  733.     {
  734.     case exactn:
  735.       if (translate)
  736.         fastmap[translate[p[1]]] = 1;
  737.       else
  738.         fastmap[p[1]] = 1;
  739.       break;
  740.  
  741.         case begline:
  742.         case before_dot:
  743.     case at_dot:
  744.     case after_dot:
  745.     case begbuf:
  746.     case endbuf:
  747.     case wordbound:
  748.     case notwordbound:
  749.     case wordbeg:
  750.     case wordend:
  751.       continue;
  752.  
  753.     case endline:
  754.       if (translate)
  755.         fastmap[translate['\n']] = 1;
  756.       else
  757.         fastmap['\n'] = 1;
  758.       if (bufp->can_be_null != 1)
  759.         bufp->can_be_null = 2;
  760.       break;
  761.  
  762.     case finalize_jump:
  763.     case maybe_finalize_jump:
  764.     case jump:
  765.     case dummy_failure_jump:
  766.       bufp->can_be_null = 1;
  767.       j = *p++ & 0377;
  768.       j += SIGN_EXTEND_CHAR (*(char *)p) << 8;
  769.       p += j + 1;        /* The 1 compensates for missing ++ above */
  770.       if (j > 0)
  771.         continue;
  772.       /* Jump backward reached implies we just went through
  773.          the body of a loop and matched nothing.
  774.          Opcode jumped to should be an on_failure_jump.
  775.          Just treat it like an ordinary jump.
  776.          For a * loop, it has pushed its failure point already;
  777.          if so, discard that as redundant.  */
  778.       if ((enum regexpcode) *p != on_failure_jump)
  779.         continue;
  780.       p++;
  781.       j = *p++ & 0377;
  782.       j += SIGN_EXTEND_CHAR (*(char *)p) << 8;
  783.       p += j + 1;        /* The 1 compensates for missing ++ above */
  784.       if (stackp != stackb && *stackp == p)
  785.         stackp--;
  786.       continue;
  787.       
  788.     case on_failure_jump:
  789.       j = *p++ & 0377;
  790.       j += SIGN_EXTEND_CHAR (*(char *)p) << 8;
  791.       p++;
  792.       *++stackp = p + j;
  793.       continue;
  794.  
  795.     case start_memory:
  796.     case stop_memory:
  797.       p++;
  798.       continue;
  799.  
  800.     case duplicate:
  801.       bufp->can_be_null = 1;
  802.       fastmap['\n'] = 1;
  803.     case anychar:
  804.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  805.         if (j != '\n')
  806.           fastmap[j] = 1;
  807.       if (bufp->can_be_null)
  808.         return;
  809.       /* Don't return; check the alternative paths
  810.          so we can set can_be_null if appropriate.  */
  811.       break;
  812.  
  813.     case wordchar:
  814.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  815.         if (SYNTAX (syntax_table, j) == Sword)
  816.           fastmap[j] = 1;
  817.       break;
  818.  
  819.     case notwordchar:
  820.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  821.         if (SYNTAX (syntax_table, j) != Sword)
  822.           fastmap[j] = 1;
  823.       break;
  824.  
  825. #ifdef emacs
  826.     case syntaxspec:
  827.       k = *p++;
  828.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  829.         if (SYNTAX (syntax_table, j) == (enum syntaxcode) k)
  830.           fastmap[j] = 1;
  831.       break;
  832.  
  833.     case notsyntaxspec:
  834.       k = *p++;
  835.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  836.         if (SYNTAX (syntax_table, j) != (enum syntaxcode) k)
  837.           fastmap[j] = 1;
  838.       break;
  839. #endif /* emacs */
  840.  
  841.     case charset:
  842.       for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  843.         if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
  844.           {
  845.         if (translate)
  846.           fastmap[translate[j]] = 1;
  847.         else
  848.           fastmap[j] = 1;
  849.           }
  850.       break;
  851.  
  852.     case charset_not:
  853.       /* Chars beyond end of map must be allowed */
  854.       for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
  855.         if (translate)
  856.           fastmap[translate[j]] = 1;
  857.         else
  858.           fastmap[j] = 1;
  859.  
  860.       for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  861.         if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
  862.           {
  863.         if (translate)
  864.           fastmap[translate[j]] = 1;
  865.         else
  866.           fastmap[j] = 1;
  867.           }
  868.       break;
  869.     case unused:
  870.       break;;
  871.     }
  872.  
  873.       /* Get here means we have successfully found the possible starting characters
  874.      of one path of the pattern.  We need not follow this path any farther.
  875.      Instead, look at the next alternative remembered in the stack. */
  876.       if (stackp != stackb)
  877.     p = *stackp--;
  878.       else
  879.     break;
  880.     }
  881. }
  882.  
  883. /* Like re_search_2, below, but only one string is specified. */
  884.  
  885. int
  886. re_search (struct re_pattern_buffer *pbufp,
  887.        char *string,
  888.        int size,
  889.        int startpos,
  890.        int range,
  891.        struct re_registers *regs)
  892. {
  893.   return re_search_2 (pbufp, 0, 0, string, size, startpos, range, regs, size);
  894. }
  895.  
  896. /* Like re_match_2 but tries first a match starting at index STARTPOS,
  897.    then at STARTPOS + 1, and so on.
  898.    RANGE is the number of places to try before giving up.
  899.    If RANGE is negative, the starting positions tried are
  900.     STARTPOS, STARTPOS - 1, etc.
  901.    It is up to the caller to make sure that range is not so large
  902.    as to take the starting position outside of the input strings.
  903.  
  904. The value returned is the position at which the match was found,
  905.  or -1 if no match was found,
  906.  or -2 if error (such as failure stack overflow).  */
  907.  
  908. int
  909. re_search_2 (struct re_pattern_buffer *pbufp, char *string1, int size1,
  910.          char *string2, int size2, int startpos, int range,
  911.          struct re_registers *regs, int mstop)
  912. {
  913.   char *fastmap = pbufp->fastmap;
  914.   unsigned char *translate = (unsigned char *) pbufp->translate;
  915.   int total = size1 + size2;
  916.   int val;
  917. #ifdef REGEX_BEGLINE_CHECK
  918.   int anchored_at_begline = 0;
  919. #endif
  920.  
  921.   /* Update the fastmap now if not correct already */
  922.   if (fastmap && !pbufp->fastmap_accurate)
  923.     re_compile_fastmap (pbufp);
  924.   
  925.   /* Don't waste time in a long search for a pattern
  926.      that says it is anchored at beginning of buffer.  */
  927.   if (pbufp->used > 0 && (enum regexpcode) pbufp->buffer[0] == begbuf
  928.       && range > 0)
  929.     {
  930.       if (startpos > 0)
  931.     return -1;
  932.       else
  933.     range = 1;
  934.     }
  935.  
  936. #ifdef REGEX_BEGLINE_CHECK
  937.   {
  938.     int i=0;
  939.  
  940.     while (i < pbufp->used)
  941.       {
  942.     if (pbufp->buffer[i] == start_memory ||
  943.         pbufp->buffer[i] == stop_memory)
  944.       i += 2;
  945.     else
  946.       break;
  947.       }
  948.     anchored_at_begline = i < pbufp->used && pbufp->buffer[i] == begline;
  949.   }
  950. #endif
  951.  
  952.   while (1)
  953.     {
  954. #ifdef REGEX_BEGLINE_CHECK
  955.       /* If the regex is anchored at the beginning of a line (i.e. with a ^),
  956.      then we can speed things up by skipping to the next beginning-of-
  957.      line. */
  958.       if (anchored_at_begline && startpos > 0 && startpos != size1 &&
  959.       range > 0)
  960.     {
  961.       /* whose stupid idea was it anyway to make this
  962.          function take two strings to match?? */
  963.       int lim = 0;
  964.       unsigned char *p;
  965.       int irange = range;
  966.       if (startpos < size1 && startpos + range >= size1)
  967.         lim = range - (size1 - startpos);
  968.  
  969.       p = ((unsigned char *)
  970.            &(startpos >= size1 ? string2 - size1 : string1)[startpos]);
  971.       p--;
  972.  
  973.       if (translate)
  974.         {
  975.           while (range > lim && translate[*p++] != '\n')
  976.         range--;
  977.         }
  978.       else
  979.         {
  980.           while (range > lim && *p++ != '\n')
  981.         range--;
  982.         }
  983.       startpos += irange - range;
  984.     }
  985. #endif /* REGEXP_BEGLINE_CHECK */
  986.       
  987.       /* If a fastmap is supplied, skip quickly over characters
  988.      that cannot possibly be the start of a match.
  989.      Note, however, that if the pattern can possibly match
  990.      the null string, we must test it at each starting point
  991.      so that we take the first null string we get.  */
  992.  
  993.       if (fastmap && startpos < total && pbufp->can_be_null != 1)
  994.     {
  995.       if (range > 0)
  996.         {
  997.           int lim = 0;
  998.           unsigned char *p;
  999.           int irange = range;
  1000.           if (startpos < size1 && startpos + range >= size1)
  1001.         lim = range - (size1 - startpos);
  1002.  
  1003.           p = ((unsigned char *)
  1004.            &(startpos >= size1 ? string2 - size1 : string1)[startpos]);
  1005.  
  1006.           if (translate)
  1007.         {
  1008.           while (range > lim && !fastmap[translate[*p++]])
  1009.             range--;
  1010.         }
  1011.           else
  1012.         {
  1013.           while (range > lim && !fastmap[*p++])
  1014.             range--;
  1015.         }
  1016.           startpos += irange - range;
  1017.         }
  1018.       else
  1019.         {
  1020.           unsigned char c;
  1021.           if (startpos >= size1)
  1022.         c = string2[startpos - size1];
  1023.           else
  1024.         c = string1[startpos];
  1025.           c &= 0xff;
  1026.           if (translate ? !fastmap[translate[c]] : !fastmap[c])
  1027.         goto advance;
  1028.         }
  1029.     }
  1030.  
  1031.       if (range >= 0 && startpos == total
  1032.       && fastmap && pbufp->can_be_null == 0)
  1033.     return -1;
  1034.  
  1035. #ifdef emacs /* XEmacs added, w/removal of immediate_quit */
  1036.       if (!no_quit_in_re_search)
  1037.     QUIT;
  1038. #endif
  1039.       val = re_match_2 (pbufp, (unsigned char *) string1, size1,
  1040.             (unsigned char *) string2, size2, startpos, regs,
  1041.             mstop);
  1042.       /* Propagate error indication if worse than mere failure.  */
  1043.       if (val == -2)
  1044.     return -2;
  1045.       /* Return position on success.  */
  1046.       if (0 <= val)
  1047.     return startpos;
  1048.  
  1049. #ifdef C_ALLOCA
  1050.       alloca (0);
  1051. #endif /* C_ALLOCA */
  1052.  
  1053.     advance:
  1054.       if (!range) break;
  1055.       if (range > 0) range--, startpos++; else range++, startpos--;
  1056.     }
  1057.   return -1;
  1058. }
  1059.  
  1060. #ifndef emacs   /* emacs never uses this */
  1061. int
  1062. re_match (pbufp, string, size, pos, regs)
  1063.      struct re_pattern_buffer *pbufp;
  1064.      char *string;
  1065.      int size, pos;
  1066.      struct re_registers *regs;
  1067. {
  1068.   return re_match_2 (pbufp, 0, 0, string, size, pos, regs, size);
  1069. }
  1070. #endif /* emacs */
  1071.  
  1072. /* Maximum size of failure stack.  Beyond this, overflow is an error.  */
  1073.  
  1074. /* #### This is 2000 in FSF Emacs but they also use a multiplier in
  1075.    conjunction with it which ends up giving a much higher effective
  1076.    value.  We were overflowing this too soon so for now I've just
  1077.    chosen a multiplier of 20 (originally 10 was chosen but that wasn't
  1078.    enough). */
  1079. int re_max_failures = 40000;
  1080.  
  1081. static int
  1082. bcmp_translate (unsigned char *s1, unsigned char *s2, int len,
  1083.         unsigned char *translate);
  1084.  
  1085. /* Match the pattern described by PBUFP
  1086.    against data which is the virtual concatenation of STRING1 and STRING2.
  1087.    SIZE1 and SIZE2 are the sizes of the two data strings.
  1088.    Start the match at position POS.
  1089.    Do not consider matching past the position MSTOP.
  1090.  
  1091.    If pbufp->fastmap is nonzero, then it had better be up to date.
  1092.  
  1093.    The reason that the data to match are specified as two components
  1094.    which are to be regarded as concatenated
  1095.    is so this function can be used directly on the contents of an Emacs buffer.
  1096.  
  1097.    -1 is returned if there is no match.  -2 is returned if there is
  1098.    an error (such as match stack overflow).  Otherwise the value is the length
  1099.    of the substring which was matched.  */
  1100.  
  1101. int
  1102. re_match_2 (struct re_pattern_buffer *pbufp, unsigned char *string1, int size1,
  1103.         unsigned char *string2, int size2, int pos,
  1104.         struct re_registers *regs, int mstop)
  1105. {
  1106.   unsigned char *p = (unsigned char *) pbufp->buffer;
  1107.   unsigned char *pend = p + pbufp->used;
  1108.   /* End of first string */
  1109.   unsigned char *end1;
  1110.   /* End of second string */
  1111.   unsigned char *end2;
  1112.   /* Pointer just past last char to consider matching */
  1113.   unsigned char *end_match_1, *end_match_2;
  1114.   unsigned char *d, *dend;
  1115.   int mcnt;
  1116.   unsigned char *translate = (unsigned char *) pbufp->translate;
  1117. #ifdef emacs
  1118.   Lisp_Object syntax_table = current_buffer->syntax_table;
  1119. #endif
  1120.  
  1121.  /* Failure point stack.  Each place that can handle a failure further down the line
  1122.     pushes a failure point on this stack.  It consists of two char *'s.
  1123.     The first one pushed is where to resume scanning the pattern;
  1124.     the second pushed is where to resume scanning the strings.
  1125.     If the latter is zero, the failure point is a "dummy".
  1126.     If a failure happens and the innermost failure point is dormant,
  1127.     it discards that failure point and tries the next one. */
  1128.  
  1129.   unsigned char *initial_stack[2 * NFAILURES];
  1130.   unsigned char **stackb = initial_stack;
  1131.   unsigned char **stackp = stackb, **stacke = &stackb[2 * NFAILURES];
  1132.  
  1133.   /* Information on the "contents" of registers.
  1134.      These are pointers into the input strings; they record
  1135.      just what was matched (on this attempt) by some part of the pattern.
  1136.      The start_memory command stores the start of a register's contents
  1137.      and the stop_memory command stores the end.
  1138.  
  1139.      At that point, regstart[regnum] points to the first character in
  1140.      the register, regend[regnum] points to the first character beyond
  1141.      the end of the register, regstart_seg1[regnum] is true iff
  1142.      regstart[regnum] points into string1, and regend_seg1[regnum] is
  1143.      true iff regend[regnum] points into string1.  */
  1144.  
  1145.   unsigned char *regstart[RE_NREGS];
  1146.   unsigned char *regend[RE_NREGS];
  1147.   unsigned char regstart_seg1[RE_NREGS], regend_seg1[RE_NREGS];
  1148.  
  1149.   /* This function is used heavily.  Quantify consistently shows it as
  1150.      one of the top 5 contributors to running time, often it is the
  1151.      top contributor.  Quantify also shows that 40% of the execution
  1152.      time is caused by the initialization of the regend array.
  1153.      However, further investigation shows that that array is not used
  1154.      more often than it is.  So, we now only initialize it if we know
  1155.      we are actually going to use it. */
  1156.   int regend_initialized = 0;
  1157.  
  1158. /* Initialize \) text positions to -1 to mark ones that no \( or \)
  1159.    has been seen for.  */
  1160. #define INIT_REGEND                            \
  1161.   do {                                    \
  1162.     if (!regend_initialized)                        \
  1163.       {                                    \
  1164.     memset (regend, -1, RE_NREGS * sizeof (unsigned char *));    \
  1165.     regend_initialized = 1;                        \
  1166.       }                                    \
  1167.   } while (0)
  1168.  
  1169.   /* Set up pointers to ends of strings.
  1170.      Don't allow the second string to be empty unless both are empty.  */
  1171.   if (!size2)
  1172.     {
  1173.       string2 = string1;
  1174.       size2 = size1;
  1175.       string1 = 0;
  1176.       size1 = 0;
  1177.     }
  1178.   end1 = string1 + size1;
  1179.   end2 = string2 + size2;
  1180.  
  1181.   /* Compute where to stop matching, within the two strings */
  1182.   if (mstop <= size1)
  1183.     {
  1184.       end_match_1 = string1 + mstop;
  1185.       end_match_2 = string2;
  1186.     }
  1187.   else
  1188.     {
  1189.       end_match_1 = end1;
  1190.       end_match_2 = string2 + mstop - size1;
  1191.     }
  1192.  
  1193.   /* `p' scans through the pattern as `d' scans through the data.
  1194.      `dend' is the end of the input string that `d' points within.
  1195.      `d' is advanced into the following input string whenever necessary,
  1196.      but this happens before fetching;
  1197.      therefore, at the beginning of the loop,
  1198.      `d' can be pointing at the end of a string,
  1199.      but it cannot equal string2.  */
  1200.  
  1201.   if (pos <= size1)
  1202.     d = string1 + pos, dend = end_match_1;
  1203.   else
  1204.     d = string2 + pos - size1, dend = end_match_2;
  1205.  
  1206. /* Write PREFETCH; just before fetching a character with *d.  */
  1207. #define PREFETCH \
  1208.  while (d == dend)                            \
  1209.   { if (dend == end_match_2) goto fail;  /* end of string2 => failure */   \
  1210.     d = string2;  /* end of string1 => advance to string2. */       \
  1211.     dend = end_match_2; }
  1212.  
  1213.   /* This loop loops over pattern commands.
  1214.      It exits by returning from the function if match is complete,
  1215.      or it drops through if match fails at this starting point in the input data. */
  1216.  
  1217.   while (1)
  1218.     {
  1219.       if (p == pend)
  1220.     /* End of pattern means we have succeeded! */
  1221.     {
  1222.       /* If caller wants register contents data back, convert it to indices */
  1223.       if (regs)
  1224.         {
  1225.           INIT_REGEND;
  1226.  
  1227.            regs->start[0] = pos;
  1228.            if (dend == end_match_1)
  1229.          regs->end[0] = d - string1;
  1230.            else
  1231.          regs->end[0] = d - string2 + size1;
  1232.            for (mcnt = 1; mcnt < RE_NREGS; mcnt++)
  1233.         {
  1234.           if (regend[mcnt] == (unsigned char *) -1)
  1235.             {
  1236.               regs->start[mcnt] = -1;
  1237.               regs->end[mcnt] = -1;
  1238.               continue;
  1239.             }
  1240.            if (regstart_seg1[mcnt])
  1241.             regs->start[mcnt] = regstart[mcnt] - string1;
  1242.           else
  1243.             regs->start[mcnt] = regstart[mcnt] - string2 + size1;
  1244.            if (regend_seg1[mcnt])
  1245.             regs->end[mcnt] = regend[mcnt] - string1;
  1246.           else
  1247.             regs->end[mcnt] = regend[mcnt] - string2 + size1;
  1248.         }
  1249.         }
  1250.        if (dend == end_match_1)
  1251.         return (d - string1 - pos);
  1252.       else
  1253.         return d - string2 + size1 - pos;
  1254.     }
  1255.  
  1256.       /* Otherwise match next pattern command */
  1257. #ifdef SWITCH_ENUM_BUG
  1258.       switch ((int) ((enum regexpcode) *p++))
  1259. #else
  1260.       switch ((enum regexpcode) *p++)
  1261. #endif
  1262.     {
  1263.  
  1264.     /* \( is represented by a start_memory, \) by a stop_memory.
  1265.         Both of those commands contain a "register number" argument.
  1266.         The text matched within the \( and \) is recorded under that number.
  1267.         Then, \<digit> turns into a `duplicate' command which
  1268.         is followed by the numeric value of <digit> as the register number. */
  1269.  
  1270.     case start_memory:
  1271.       regstart[*p] = d;
  1272.        regstart_seg1[*p++] = (dend == end_match_1);
  1273.       break;
  1274.  
  1275.     case stop_memory:
  1276.       INIT_REGEND;
  1277.       regend[*p] = d;
  1278.        regend_seg1[*p++] = (dend == end_match_1);
  1279.       break;
  1280.  
  1281.     case duplicate:
  1282.       {
  1283.         int regno = *p++;   /* Get which register to match against */
  1284.         unsigned char *d2, *dend2;
  1285.  
  1286.         INIT_REGEND;
  1287.         /* Don't allow matching a register that hasn't been used.
  1288.            This isn't fully reliable in the current version,
  1289.            but it is better than crashing.  */
  1290.         if ((long) regend[regno] <= -1)
  1291.           goto fail;
  1292.  
  1293.         d2 = regstart[regno];
  1294.          dend2 = ((regstart_seg1[regno] == regend_seg1[regno])
  1295.              ? regend[regno] : end_match_1);
  1296.         while (1)
  1297.           {
  1298.         /* Advance to next segment in register contents, if necessary */
  1299.         while (d2 == dend2)
  1300.           {
  1301.             if (dend2 == end_match_2) break;
  1302.             if (dend2 == regend[regno]) break;
  1303.             d2 = string2, dend2 = regend[regno];  /* end of string1 => advance to string2. */
  1304.           }
  1305.         /* At end of register contents => success */
  1306.         if (d2 == dend2) break;
  1307.  
  1308.         /* Advance to next segment in data being matched, if necessary */
  1309.         PREFETCH;
  1310.  
  1311.         /* mcnt gets # consecutive chars to compare */
  1312.         mcnt = dend - d;
  1313.         if (mcnt > dend2 - d2)
  1314.           mcnt = dend2 - d2;
  1315.         /* Compare that many; failure if mismatch, else skip them. */
  1316.         if (translate
  1317.             ? bcmp_translate (d, d2, mcnt, translate)
  1318.             : memcmp (d, d2, mcnt))
  1319.           goto fail;
  1320.         d += mcnt, d2 += mcnt;
  1321.           }
  1322.       }
  1323.       break;
  1324.  
  1325.     case anychar:
  1326.       /* fetch a data character */
  1327.       PREFETCH;
  1328.       /* Match anything but a newline.  */
  1329.       if ((translate ? translate[*d++] : *d++) == '\n')
  1330.         goto fail;
  1331.       break;
  1332.  
  1333.     case charset:
  1334.     case charset_not:
  1335.       {
  1336.         /* Nonzero for charset_not */
  1337.         int not = 0;
  1338.         int c;
  1339.         if (*(p - 1) == (unsigned char) charset_not)
  1340.           not = 1;
  1341.  
  1342.         /* fetch a data character */
  1343.         PREFETCH;
  1344.  
  1345.         if (translate)
  1346.           c = translate [*d];
  1347.         else
  1348.           c = *d;
  1349.  
  1350.         if (c <  (int) (*p * BYTEWIDTH)
  1351.         && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  1352.           not = !not;
  1353.  
  1354.         p += 1 + *p;
  1355.  
  1356.         if (!not) goto fail;
  1357.         d++;
  1358.         break;
  1359.       }
  1360.  
  1361.     case begline:
  1362.       /* #### won't this fail if a translation for '\n' is given? */
  1363.       if (d == string1 || d[-1] == '\n')
  1364.         break;
  1365.       goto fail;
  1366.  
  1367.     case endline:
  1368.       if (d == end2
  1369.           || (d == end1 ? (size2 == 0 || *string2 == '\n') : *d == '\n'))
  1370.         break;
  1371.       goto fail;
  1372.  
  1373.     /* "or" constructs ("|") are handled by starting each
  1374.         alternative with an on_failure_jump that points to the
  1375.         start of the next alternative.  Each alternative except
  1376.         the last ends with a jump to the joining point.
  1377.         (Actually, each jump except for the last one really jumps
  1378.         to the following jump, because tensioning the jumps is a
  1379.         hassle.) */
  1380.  
  1381.     /* The start of a stupid repeat has an on_failure_jump that
  1382.        points past the end of the repeat text.  This makes a
  1383.        failure point so that, on failure to match a repetition,
  1384.        matching restarts past as many repetitions have been found
  1385.        with no way to fail and look for another one.  */
  1386.  
  1387.     /* A smart repeat is similar but loops back to the
  1388.        on_failure_jump so that each repetition makes another
  1389.        failure point. */
  1390.  
  1391.     case on_failure_jump:
  1392.       if (stackp == stacke)
  1393.         {
  1394.           unsigned char **stackx;
  1395.           if (stacke - stackb > re_max_failures)
  1396.         return -2;
  1397.           stackx = (unsigned char **) alloca (2 * (stacke - stackb)
  1398.                      * sizeof (char *));
  1399.           memcpy (stackx, stackb, (stacke - stackb) * sizeof (char *));
  1400.           stackp = stackx + (stackp - stackb);
  1401.           stacke = stackx + 2 * (stacke - stackb);
  1402.           stackb = stackx;
  1403.         }
  1404.       mcnt = *p++ & 0377;
  1405.       mcnt += SIGN_EXTEND_CHAR (*(char *)p) << 8;
  1406.       p++;
  1407.       *stackp++ = mcnt + p;
  1408.       *stackp++ = d;
  1409.       break;
  1410.  
  1411.     /* The end of a smart repeat has an maybe_finalize_jump back.
  1412.        Change it either to a finalize_jump or an ordinary jump. */
  1413.  
  1414.     case maybe_finalize_jump:
  1415.       mcnt = *p++ & 0377;
  1416.       mcnt += SIGN_EXTEND_CHAR (*(char *)p) << 8;
  1417.       p++;
  1418.       /* Compare what follows with the begining of the repeat.
  1419.          If we can establish that there is nothing that they would
  1420.          both match, we can change to finalize_jump */
  1421.       if (p == pend)
  1422.         p[-3] = (unsigned char) finalize_jump;
  1423.       else if (*p == (unsigned char) exactn
  1424.            || *p == (unsigned char) endline)
  1425.         {
  1426.           int c = *p == (unsigned char) endline ? '\n' : p[2];
  1427.           unsigned char *p1 = p + mcnt;
  1428.           /* p1[0] ... p1[2] are an on_failure_jump.
  1429.          Examine what follows that */
  1430.           if (p1[3] == (unsigned char) exactn && p1[5] != c)
  1431.         p[-3] = (unsigned char) finalize_jump;
  1432.           else if (p1[3] == (unsigned char) charset
  1433.                || p1[3] == (unsigned char) charset_not)
  1434.         {
  1435.           int not = p1[3] == (unsigned char) charset_not;
  1436.           if (c <  (int) (p1[4] * BYTEWIDTH)
  1437.               && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  1438.             not = !not;
  1439.           /* not is 1 if c would match */
  1440.           /* That means it is not safe to finalize */
  1441.           if (!not)
  1442.             p[-3] = (unsigned char) finalize_jump;
  1443.         }
  1444.         }
  1445.       p -= 2;
  1446.       if (p[-1] != (unsigned char) finalize_jump)
  1447.         {
  1448.           p[-1] = (unsigned char) jump;
  1449.           goto nofinalize;
  1450.         }
  1451.  
  1452.     /* The end of a stupid repeat has a finalize-jump
  1453.        back to the start, where another failure point will be made
  1454.        which will point after all the repetitions found so far. */
  1455.  
  1456.     case finalize_jump:
  1457.       stackp -= 2;
  1458.  
  1459.     case jump:
  1460.     nofinalize:
  1461.       mcnt = *p++ & 0377;
  1462.       mcnt += SIGN_EXTEND_CHAR (*(char *)p) << 8;
  1463.       p += mcnt + 1;    /* The 1 compensates for missing ++ above */
  1464.       break;
  1465.  
  1466.     case dummy_failure_jump:
  1467.       if (stackp == stacke)
  1468.         {
  1469.           unsigned char **stackx
  1470.         = (unsigned char **) alloca (2 * (stacke - stackb)
  1471.                          * sizeof (char *));
  1472.           memcpy (stackx, stackb, (stacke - stackb) * sizeof (char *));
  1473.           stackp = stackx + (stackp - stackb);
  1474.           stacke = stackx + 2 * (stacke - stackb);
  1475.           stackb = stackx;
  1476.         }
  1477.       *stackp++ = 0;
  1478.       *stackp++ = 0;
  1479.       goto nofinalize;
  1480.  
  1481.     case wordbound:
  1482.       if (d == string1  /* Points to first char */
  1483.           || d == end2  /* Points to end */
  1484.           || (d == end1 && size2 == 0)) /* Points to end */
  1485.         break;
  1486.       if ((SYNTAX (syntax_table, d[-1]) == Sword)
  1487.           != (SYNTAX (syntax_table, d == end1 ? *string2 : *d) == Sword))
  1488.         break;
  1489.       goto fail;
  1490.  
  1491.     case notwordbound:
  1492.       if (d == string1  /* Points to first char */
  1493.           || d == end2  /* Points to end */
  1494.           || (d == end1 && size2 == 0)) /* Points to end */
  1495.         goto fail;
  1496.       if ((SYNTAX (syntax_table, d[-1]) == Sword)
  1497.           != (SYNTAX (syntax_table, d == end1 ? *string2 : *d) == Sword))
  1498.         goto fail;
  1499.       break;
  1500.  
  1501.     case wordbeg:
  1502.       if (d == end2  /* Points to end */
  1503.           || (d == end1 && size2 == 0) /* Points to end */
  1504.           || SYNTAX (syntax_table, * (d == end1 ? string2 : d)) != Sword) /* Next char not a letter */
  1505.         goto fail;
  1506.       if (d == string1  /* Points to first char */
  1507.           || SYNTAX (syntax_table, d[-1]) != Sword)  /* prev char not letter */
  1508.         break;
  1509.       goto fail;
  1510.  
  1511.     case wordend:
  1512.       if (d == string1  /* Points to first char */
  1513.           || SYNTAX (syntax_table, d[-1]) != Sword)  /* prev char not letter */
  1514.         goto fail;
  1515.       if (d == end2  /* Points to end */
  1516.           || (d == end1 && size2 == 0) /* Points to end */
  1517.           || SYNTAX (syntax_table, d == end1 ? *string2 : *d) != Sword) /* Next char not a letter */
  1518.         break;
  1519.       goto fail;
  1520.  
  1521. #ifdef emacs
  1522.     case before_dot:
  1523.       if (BI_BUF_PTR_BYTE_POS (current_buffer, d) >=
  1524.           BI_BUF_PT (current_buffer))
  1525.         goto fail;
  1526.       break;
  1527.  
  1528.     case at_dot:
  1529.       if (BI_BUF_PTR_BYTE_POS (current_buffer, d) !=
  1530.           BI_BUF_PT (current_buffer))
  1531.         goto fail;
  1532.       break;
  1533.  
  1534.     case after_dot:
  1535.       if (BI_BUF_PTR_BYTE_POS (current_buffer, d) <=
  1536.           BI_BUF_PT (current_buffer))
  1537.         goto fail;
  1538.       break;
  1539.  
  1540.     case wordchar:
  1541.       mcnt = (int) Sword;
  1542.       goto matchsyntax;
  1543.  
  1544.     case syntaxspec:
  1545.       mcnt = *p++;
  1546.     matchsyntax:
  1547.       PREFETCH;
  1548.       if (SYNTAX (syntax_table, *d++) != (enum syntaxcode) mcnt)
  1549.             goto fail;
  1550.       break;
  1551.       
  1552.     case notwordchar:
  1553.       mcnt = (int) Sword;
  1554.       goto matchnotsyntax;
  1555.  
  1556.     case notsyntaxspec:
  1557.       mcnt = *p++;
  1558.     matchnotsyntax:
  1559.       PREFETCH;
  1560.       if (SYNTAX (syntax_table, *d++) == (enum syntaxcode) mcnt)
  1561.             goto fail;
  1562.       break;
  1563. #else
  1564.     case wordchar:
  1565.       PREFETCH;
  1566.       if (SYNTAX (syntax_table, *d++) == 0) goto fail;
  1567.       break;
  1568.       
  1569.     case notwordchar:
  1570.       PREFETCH;
  1571.       if (SYNTAX (syntax_table, *d++) != 0) goto fail;
  1572.       break;
  1573. #endif /* not emacs */
  1574.  
  1575.     case begbuf:
  1576.       if (d == string1)    /* Note, d cannot equal string2 */
  1577.         break;        /* unless string1 == string2.  */
  1578.       goto fail;
  1579.  
  1580.     case endbuf:
  1581.       if (d == end2 || (d == end1 && size2 == 0))
  1582.         break;
  1583.       goto fail;
  1584.  
  1585.     case exactn:
  1586.       /* Match the next few pattern characters exactly.
  1587.          mcnt is how many characters to match. */
  1588.       mcnt = *p++;
  1589.       if (translate)
  1590.         {
  1591.           do
  1592.         {
  1593.           PREFETCH;
  1594.           if (translate[*d++] != *p++) goto fail;
  1595.         }
  1596.           while (--mcnt);
  1597.         }
  1598.       else
  1599.         {
  1600.           do
  1601.         {
  1602.           PREFETCH;
  1603.           if (*d++ != *p++) goto fail;
  1604.         }
  1605.           while (--mcnt);
  1606.         }
  1607.       break;
  1608.         case unused:
  1609.           break;
  1610.     }
  1611.       continue;    /* Successfully matched one pattern command; keep matching */
  1612.  
  1613.       /* Jump here if any matching operation fails. */
  1614.     fail:
  1615.       if (stackp != stackb)
  1616.     /* A restart point is known.  Restart there and pop it. */
  1617.     {
  1618.       if (!stackp[-2])
  1619.         {
  1620.           /* If innermost failure point is dormant, flush it and
  1621.                  keep looking */
  1622.           stackp -= 2;
  1623.           goto fail;
  1624.         }
  1625.       d = *--stackp;
  1626.       p = *--stackp;
  1627.       if (d >= string1 && d <= end1)
  1628.         dend = end_match_1;
  1629.     }
  1630.       else break;   /* Matching at this starting point really fails! */
  1631.     }
  1632.   return -1;         /* Failure to match */
  1633. }
  1634. #undef INIT_REGEND
  1635.  
  1636. static int
  1637. bcmp_translate (unsigned char *s1, unsigned char *s2, int len,
  1638.         unsigned char *translate)
  1639. {
  1640.   unsigned char *p1 = s1, *p2 = s2;
  1641.   while (len)
  1642.     {
  1643.       if (translate [*p1++] != translate [*p2++]) return 1;
  1644.       len--;
  1645.     }
  1646.   return 0;
  1647. }
  1648.  
  1649. /* Entry points compatible with bsd4.2 regex library */
  1650.  
  1651. #ifndef emacs
  1652.  
  1653. static struct re_pattern_buffer re_comp_buf;
  1654.  
  1655. char *
  1656. re_comp (s)
  1657.      char *s;
  1658. {
  1659.   if (!s)
  1660.     {
  1661.       if (!re_comp_buf.buffer)
  1662.     return GETTEXT ("No previous regular expression");
  1663.       return 0;
  1664.     }
  1665.  
  1666.   if (!re_comp_buf.buffer)
  1667.     {
  1668.       if (!(re_comp_buf.buffer = (char *) xmalloc (200)))
  1669.     return GETTEXT ("Memory exhausted");
  1670.       re_comp_buf.allocated = 200;
  1671.       if (!(re_comp_buf.fastmap = (char *) xmalloc (1 << BYTEWIDTH)))
  1672.     return GETTEXT ("Memory exhausted");
  1673.     }
  1674.   return re_compile_pattern (s, strlen (s), &re_comp_buf);
  1675. }
  1676.  
  1677. int
  1678. re_exec (s)
  1679.      char *s;
  1680. {
  1681.   int len = strlen (s);
  1682.   return 0 <= re_search (&re_comp_buf, s, len, 0, len, 0);
  1683. }
  1684.  
  1685. #endif /* emacs */
  1686.  
  1687. #ifdef test
  1688.  
  1689. #include <stdio.h>
  1690.  
  1691. /* Indexed by a character, gives the upper case equivalent of the character */
  1692.  
  1693. static char upcase[0400] = 
  1694.   { 000, 001, 002, 003, 004, 005, 006, 007,
  1695.     010, 011, 012, 013, 014, 015, 016, 017,
  1696.     020, 021, 022, 023, 024, 025, 026, 027,
  1697.     030, 031, 032, 033, 034, 035, 036, 037,
  1698.     040, 041, 042, 043, 044, 045, 046, 047,
  1699.     050, 051, 052, 053, 054, 055, 056, 057,
  1700.     060, 061, 062, 063, 064, 065, 066, 067,
  1701.     070, 071, 072, 073, 074, 075, 076, 077,
  1702.     0100, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
  1703.     0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117,
  1704.     0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  1705.     0130, 0131, 0132, 0133, 0134, 0135, 0136, 0137,
  1706.     0140, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
  1707.     0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117,
  1708.     0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  1709.     0130, 0131, 0132, 0173, 0174, 0175, 0176, 0177,
  1710.     0200, 0201, 0202, 0203, 0204, 0205, 0206, 0207,
  1711.     0210, 0211, 0212, 0213, 0214, 0215, 0216, 0217,
  1712.     0220, 0221, 0222, 0223, 0224, 0225, 0226, 0227,
  1713.     0230, 0231, 0232, 0233, 0234, 0235, 0236, 0237,
  1714.     0240, 0241, 0242, 0243, 0244, 0245, 0246, 0247,
  1715.     0250, 0251, 0252, 0253, 0254, 0255, 0256, 0257,
  1716.     0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267,
  1717.     0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277,
  1718.     0300, 0301, 0302, 0303, 0304, 0305, 0306, 0307,
  1719.     0310, 0311, 0312, 0313, 0314, 0315, 0316, 0317,
  1720.     0320, 0321, 0322, 0323, 0324, 0325, 0326, 0327,
  1721.     0330, 0331, 0332, 0333, 0334, 0335, 0336, 0337,
  1722.     0340, 0341, 0342, 0343, 0344, 0345, 0346, 0347,
  1723.     0350, 0351, 0352, 0353, 0354, 0355, 0356, 0357,
  1724.     0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367,
  1725.     0370, 0371, 0372, 0373, 0374, 0375, 0376, 0377
  1726.   };
  1727.  
  1728. main (argc, argv)
  1729.      int argc;
  1730.      char **argv;
  1731. {
  1732.   char pat[80];
  1733.   struct re_pattern_buffer buf;
  1734.   int i;
  1735.   char c;
  1736.   char fastmap[(1 << BYTEWIDTH)];
  1737.  
  1738.   /* Allow a command argument to specify the style of syntax.  */
  1739.   if (argc > 1)
  1740.     obscure_syntax = atoi (argv[1]);
  1741.  
  1742.   buf.allocated = 40;
  1743.   buf.buffer = (char *) xmalloc (buf.allocated);
  1744.   buf.fastmap = fastmap;
  1745.   buf.translate = upcase;
  1746.  
  1747.   while (1)
  1748.     {
  1749.       gets (pat);
  1750.  
  1751.       if (*pat)
  1752.     {
  1753.           re_compile_pattern (pat, strlen(pat), &buf);
  1754.  
  1755.       for (i = 0; i < buf.used; i++)
  1756.         printchar (buf.buffer[i]);
  1757.  
  1758.       putchar ('\n');
  1759.  
  1760.       stdout_out ("%d allocated, %d used.\n",
  1761.           buf.allocated, buf.used);
  1762.  
  1763.       re_compile_fastmap (&buf);
  1764.       stdout_out ("Allowed by fastmap: ");
  1765.       for (i = 0; i < (1 << BYTEWIDTH); i++)
  1766.         if (fastmap[i]) printchar (i);
  1767.       putchar ('\n');
  1768.     }
  1769.  
  1770.       gets (pat);    /* Now read the string to match against */
  1771.  
  1772.       i = re_match (&buf, pat, strlen (pat), 0, 0);
  1773.       stdout_out ("Match value %d.\n", i);
  1774.     }
  1775. }
  1776.  
  1777. #ifdef NOTDEF
  1778. print_buf (bufp)
  1779.      struct re_pattern_buffer *bufp;
  1780. {
  1781.   int i;
  1782.  
  1783.   stdout_out ("buf is :\n----------------\n");
  1784.   for (i = 0; i < bufp->used; i++)
  1785.     printchar (bufp->buffer[i]);
  1786.   
  1787.   stdout_out ("\n%d allocated, %d used.\n", bufp->allocated, bufp->used);
  1788.   
  1789.   stdout_out ("Allowed by fastmap: ");
  1790.   for (i = 0; i < (1 << BYTEWIDTH); i++)
  1791.     if (bufp->fastmap[i])
  1792.       printchar (i);
  1793.   stdout_out ("\nAllowed by translate: ");
  1794.   if (bufp->translate)
  1795.     for (i = 0; i < (1 << BYTEWIDTH); i++)
  1796.       if (bufp->translate[i])
  1797.     printchar (i);
  1798.   stdout_out ("\nfastmap is%s accurate\n",
  1799.       bufp->fastmap_accurate ? "" : "n't");
  1800.   stdout_out ("can %s be null\n----------",
  1801.       bufp->can_be_null ? "" : "not");
  1802. }
  1803. #endif
  1804.  
  1805. printchar (c)
  1806.      char c;
  1807. {
  1808.   if (c < 041 || c >= 0177)
  1809.     {
  1810.       putchar ('\\');
  1811.       putchar (((c >> 6) & 3) + '0');
  1812.       putchar (((c >> 3) & 7) + '0');
  1813.       putchar ((c & 7) + '0');
  1814.     }
  1815.   else
  1816.     putchar (c);
  1817. }
  1818.  
  1819. error (string)
  1820.      char *string;
  1821. {
  1822.   puts (string);
  1823.   exit (1);
  1824. }
  1825.  
  1826. #endif /* test */
  1827.